from typing import Any, Optional, Union, List
from fastapi import status
from fastapi.responses import JSONResponse

from app.schemas.base import ResponseModel, PaginationResponse


class ResponseUtil:
    """响应工具类"""

    @staticmethod
    def success(
        data: Any = None,
        message: str = "操作成功",
        code: int = 200
    ) -> ResponseModel:
        """成功响应"""
        return ResponseModel(
            code=code,
            message=message,
            data=data
        )

    @staticmethod
    def error(
        message: str = "操作失败",
        code: int = 400,
        data: Any = None
    ) -> ResponseModel:
        """错误响应"""
        return ResponseModel(
            code=code,
            message=message,
            data=data
        )

    @staticmethod
    def paginate(
        items: List[Any],
        total: int,
        page: int,
        page_size: int,
        message: str = "获取成功"
    ) -> ResponseModel:
        """分页响应"""
        pages = (total + page_size - 1) // page_size if page_size > 0 else 0

        pagination_data = PaginationResponse(
            total=total,
            page=page,
            page_size=page_size,
            pages=pages,
            items=items
        )

        return ResponseModel(
            code=200,
            message=message,
            data=pagination_data
        )

    @staticmethod
    def unauthorized(message: str = "未授权访问") -> JSONResponse:
        """未授权响应"""
        return JSONResponse(
            status_code=status.HTTP_401_UNAUTHORIZED,
            content={
                "code": 401,
                "message": message,
                "data": None
            }
        )

    @staticmethod
    def forbidden(message: str = "权限不足") -> JSONResponse:
        """禁止访问响应"""
        return JSONResponse(
            status_code=status.HTTP_403_FORBIDDEN,
            content={
                "code": 403,
                "message": message,
                "data": None
            }
        )

    @staticmethod
    def not_found(message: str = "资源不存在") -> JSONResponse:
        """资源不存在响应"""
        return JSONResponse(
            status_code=status.HTTP_404_NOT_FOUND,
            content={
                "code": 404,
                "message": message,
                "data": None
            }
        )

    @staticmethod
    def internal_error(message: str = "服务器内部错误") -> JSONResponse:
        """服务器错误响应"""
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={
                "code": 500,
                "message": message,
                "data": None
            }
        )